package com.rjgc.emallsimulation.controller;

import com.rjgc.emallsimulation.adapter.ResultAdapter;
import com.rjgc.emallsimulation.entity.User;
import com.rjgc.emallsimulation.entity.UserInfo;
import com.rjgc.emallsimulation.service.UserInfoService;
import com.rjgc.emallsimulation.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

@RestController
public class UserController {

    @Resource
    UserService userService;
    @Resource
    UserInfoService userInfoService;

    @GetMapping("/user/{phone}")
    public User getUser(
            @PathVariable("phone") String phone
    ){
        var u=userService.query().eq("phone",phone).one();
        return u;
    }

    @PutMapping("/updateUser")
    public Map<String,Object> update(
            @RequestParam("phone") String phone,
            @RequestParam("account") String account,
            @RequestParam("address") String address
    ){
        var u=userService.query().eq("phone",phone).one();
        UserInfo i=userInfoService.query().eq("phone",phone).one();
        if(i==null){
            i=new UserInfo(phone,address,new BigDecimal("0.00"));
        }
        u.setAccount(account);
        i.setAddress(address);
        var flag1=userService.saveOrUpdate(u);
        var flag2=userInfoService.saveOrUpdate(i);
        if(flag1&&flag2){
            return ResultAdapter.singleResult("editSuccess",true);
        }else {
            return ResultAdapter.singleResult("editSuccess",false);
        }
    }

    @PostMapping("/changePass")
    public Map<String,Object> changePass(
            @RequestParam("phone") String phone,
            @RequestParam("oldPassword") String opass,
            @RequestParam("newPassword") String npass
    ){
        var u=userService.query().eq("phone",phone).eq("password",opass).one();
        if (u!=null){
            u.setPassword(npass);
            userService.saveOrUpdate(u);
            return ResultAdapter.singleResult("editSuccess",true);
        }
        return ResultAdapter.singleResult("editSuccess",false);
    }

    @PutMapping("/changeBlance")
    public Map<String,Object> changeBlance(
            @RequestParam("phone") String phone,
            @RequestParam("money") BigDecimal money
    ){
        var user=userInfoService.query().eq("phone",phone).one();
        if(user!=null){
            user.setBalance(user.getBalance().add(money));
            userInfoService.saveOrUpdate(user);
            return ResultAdapter.singleResult("editSuccess",true);
        }
        return ResultAdapter.singleResult("editSuccess",false);
    }



}
